/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.net.handler;

import game.GameInstance;
import game.GameState;
import game.Player;
import java.nio.ByteBuffer;
import server.GameServer;
import server.net.Client;
import server.net.ClientConnection;
import shared.net.protocol.PacketCreator;

/**
 * This class handles observe requests from the client.
 *
 * @author Andrew Gratta <andrew.gratta@stonybrook.edu>
 * @author Vincent Tsuei
 * @version 2012-11-29
 */
public class ObserveRequestHandler implements ServerPacketHandler {

    private final String NOT_LOGGED_IN_ERROR = "Error: You are not logged in";
    private final String NOT_IN_LOBBY_ERROR = "Error: You need to be in the lobby to observe a game";
    private final String INVALID_GAME_ID_ERROR = "Error: That game does not exist";
    private final String NOT_OBSERVING_ERROR = "Error: You are not currently observing that game";

    @Override
    public int processPacket(Client client, ByteBuffer packet) {
        if (client == null || packet == null) {
            return -1;
        }
        ClientConnection connection = client.getConnection();
        if (!client.isLoggedIn()) {
            connection.queuePacketSend(PacketCreator.LOBBY.OBSERVE
                    .getObserveFailureResponse(NOT_LOGGED_IN_ERROR));
            return -1;
        }

        Player observer = client.getPlayer();

        byte type = packet.get();
        long gameID = packet.getLong();
        GameServer server = client.getGameServer();
        GameInstance game = server.getServerRegistry().getGameByID(gameID);

        if (game == null) {
            connection.queuePacketSend(PacketCreator.LOBBY.OBSERVE
                    .getObserveFailureResponse(INVALID_GAME_ID_ERROR));
            return -1;
        }
        
        if (type == 0) { //Unobserve
            if (!observer.isObserving()) {
                connection.queuePacketSend(PacketCreator.LOBBY.OBSERVE
                        .getObserveFailureResponse(NOT_OBSERVING_ERROR));
                return -1;
            }
            connection.queuePacketSend(PacketCreator.LOBBY.OBSERVE.getUnobserveSuccessResponse());
            observer.unobserveGame();
        } else if (type == 1) { //Observe
            if (!observer.isInLobby()) {
                connection.queuePacketSend(PacketCreator.LOBBY.OBSERVE
                        .getObserveFailureResponse(NOT_IN_LOBBY_ERROR));
                return -1;
            }
            connection.queuePacketSend(PacketCreator.LOBBY.OBSERVE
                    .getObserveSuccessResponse(game.getGameID(), game.getFirstPlayer().getName(), game.getSecondPlayer().getName(), 
                    game.getActivePlayer().getName(), game.getNumPiles(), game.getPiles()));
            observer.observeGame(game);
        }
        
        return 0;
    }
}
